import os
# 导入os模块，用于与操作系统进行交互，如设置环境变量

from selenium import webdriver
# 导入selenium的webdriver模块，用于自动化浏览器操作

from selenium.webdriver.common.by import By
# 导入By模块，用于定位页面元素

from selenium.webdriver.support.ui import WebDriverWait
# 导入WebDriverWait模块，用于设置显式等待，以处理动态内容加载

from selenium.webdriver.support import expected_conditions as EC
# 导入expected_conditions模块并命名为EC，用于定义等待某个条件成立

import datetime
# 导入datetime模块，用于处理日期和时间

import time
# 导入time模块，用于实现延迟操作

# ==== 设定抢购时间 （修改此处，指定抢购时间点）====
BUY_TIME = "2025-04-24 14:28:00"

# ====  标识登录状态、重试次数 ====
MAX_LOGIN_RETRY_TIMES = 6
current_retry_login_times = 0
login_success = False
buy_time_object = datetime.datetime.strptime(BUY_TIME, '%Y-%m-%d %H:%M:%S')

now_time = datetime.datetime.now()
if now_time > buy_time_object:
    print("当前已过抢购时间，请确认抢购时间是否填错...")
    exit(0)

print("正在打开chrome浏览器...")
option = webdriver.ChromeOptions()
option.add_argument('disable-infobars')
driver = webdriver.Chrome(options=option)
driver.maximize_window()
print("chrome浏览器已经打开...")


def __login_operates():
    driver.get("https://www.taobao.com")
    try:
        if driver.find_element(By.LINK_TEXT, "亲，请登录"):
            print("没登录，开始点击登录按钮...")
            driver.find_element(By.LINK_TEXT, "亲，请登录").click()
            print("请使用手机淘宝扫描屏幕上的二维码进行登录...")
            time.sleep(10)
    except Exception:
        print("已登录，开始执行跳转...")
        global login_success
        global current_retry_login_times
        login_success = True
        current_retry_login_times = 0


def login():
    print("开始尝试登录...")
    __login_operates()
    global current_retry_login_times
    while current_retry_login_times < MAX_LOGIN_RETRY_TIMES:
        current_retry_login_times += 1
        print("当前尝试登录次数：" + str(current_retry_login_times))
        __login_operates()
        if login_success:
            print("登录成功")
            break
        else:
            print("等待登录中...")

    if not login_success:
        print("规定时间内没有扫码登录淘宝成功，执行失败，退出脚本!!!")
        exit(0)

    now = datetime.datetime.now()
    print('login success:', now.strftime('%Y-%m-%d %H:%M:%S'))


def __refresh_keep_alive():
    # 重新加载购物车页面，定时操作，防止长时间不操作退出登录
    driver.get("https://cart.taobao.com/cart.htm")
    print("刷新购物车界面，防止登录超时...")
    time.sleep(60)


def keep_login_and_wait():
    print("当前距离抢购时间点还有较长时间，开始定时刷新防止登录超时...")
    while True:
        current_time = datetime.datetime.now()
        if (buy_time_object - current_time).seconds > 180:
            __refresh_keep_alive()
        else:
            print("抢购时间点将近，停止自动刷新，准备进入抢购阶段...")
            break


def buy():
    # 打开购物车
    driver.get("https://cart.taobao.com/cart.htm")
    time.sleep(1)

    try:
        # 点击购物车里全选按钮
        checkbox = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.CLASS_NAME, "cartOperationCheckbox--CIlk23mK"))
        )
        checkbox.click()
        print("已经选中购物车中全部商品 ...")
    except Exception as e:
        print("未找到全选按钮:", e)
        return  # 提前退出buy函数

    submit_succ = False
    retry_submit_times = 0
    while True:
        now = datetime.datetime.now()
        if now >= buy_time_object:
            print("到达抢购时间，开始执行抢购...尝试次数：" + str(retry_submit_times))
            if submit_succ:
                print("订单已经提交成功，请查看订单信息...")
                break
            if retry_submit_times > 50:
                print("重试抢购次数达到上限，放弃重试...")
                break

            retry_submit_times += 1

            try:
                # 点击结算按钮
                checkout_button = WebDriverWait(driver, 10).until(
                    EC.element_to_be_clickable((By.CLASS_NAME, "btn--QDjHtErD"))
                )
                checkout_button.click()
                print("已经点击结算按钮...")

                # 点击提交订单按钮
                click_submit_times = 0
                while click_submit_times < 10:
                    try:
                        submit_button = WebDriverWait(driver, 10).until(
                            EC.element_to_be_clickable((By.CLASS_NAME, 'btn--QDjHtErD'))
                        )
                        submit_button.click()
                        print("已经点击提交订单按钮")
                        submit_succ = True
                        break
                    except Exception:
                        print("没发现提交订单按钮，可能页面还没加载出来，重试...")
                        click_submit_times += 1
                        time.sleep(0.1)
            except Exception as e:
                print("点击结算按钮失败:", e)

        time.sleep(0.1)


login()
keep_login_and_wait()
buy()
print("抢购流程执行完毕，请在浏览器中查看订单信息...")
input("按回车键退出程序...")
